package git.soulbgm.controller;

import git.soulbgm.common.pojo.ResultData;
import git.soulbgm.common.pojo.ReturnCode;
import git.soulbgm.config.KeyConfig;
import git.soulbgm.pojo.User;
import git.soulbgm.utils.AesUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.apache.logging.log4j.util.Strings.*;

/**
 * @author SoulBGM
 * @date 2023-10-07
 */
@RestController
public class TestController {

    @PostMapping("test1")
    public ResultData test(@RequestBody User user) {
        return ResultData.getResultData(ReturnCode.SUCCESS, user);
    }

    @GetMapping("test2")
    public ResultData test2(User user) {
        return ResultData.getResultData(ReturnCode.SUCCESS, user);
    }

    public static final String HEADER_TOKEN = "Authorization";
    public static final String HEADER_URI_TOKEN = "at_";
    public static final String HEADER_URI = "X-Original-URI";
    public static final String PREFIX_USER_TOKEN_INFO = "token_";
    private final StringRedisTemplate redis;

    public TestController(StringRedisTemplate redisTemplate) {
        this.redis = redisTemplate;
    }

    @GetMapping("/auth/token")
    public void auth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 通过 HttpServletRequest 获取请求头中的 token
        String token = request.getHeader(HEADER_TOKEN);
        String uri = request.getHeader(HEADER_URI);
        if (isBlank(token) && isNotBlank(uri) && uri.contains(HEADER_URI_TOKEN)) {
            token = AesUtil.decrypt(uri.split(HEADER_URI_TOKEN)[1], KeyConfig.getConfig().getUniqueKey());
        }
        if (isBlank(token)) {
            response.setStatus(401);
            return;
        }
        String value = redis.opsForValue().get(PREFIX_USER_TOKEN_INFO + token);
        if (isEmpty(value)) {
            response.setStatus(403);
            return;
        }
        response.setStatus(200);
    }

    @GetMapping("/auth/addToken")
    public ResultData addToken(String token) {
        redis.opsForValue().set(PREFIX_USER_TOKEN_INFO + token, System.currentTimeMillis() + "");
        return ResultData.getResultData(ReturnCode.SUCCESS);
    }
}
